<template>
  <div class="main">
    <div class="mapInfo">
      <baidu-map
        class="map"
        ak="Az7pATeNW5vM8HmZXxDXyCCK0EeM22Hc"
        :center="center"
        :zoom="zoom"
        v="3.0"
        type="API"
        :scroll-wheel-zoom="true"
        mapType="BMAP_SATELLITE_MAP"
        @ready="ready"
      >
        <!--比例尺控件 -->
        <bm-scale anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-scale>
        <!-- 缩放工具 -->
        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
        <!-- 视图切换 -->
        <bm-map-type
          :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
          anchor="BMAP_ANCHOR_TOP_LEFT"
        ></bm-map-type>
        <!-- 定位控件 -->
        <bm-geolocation
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="true"
          :autoLocation="true"
        ></bm-geolocation>
        <!-- BMAP_ANIMATION_BOUNCE  BMAP_ANIMATION_DROP -->
        <!-- :key="vertexes.data.vertexId" -->
        <!-- 设置为 false，使标记不可拖动 -->
        <bm-marker
          v-for="(vertex, index) in vertexData"
          :key="index"
          :position="{ lng: vertex.longitude, lat: vertex.latitude }"
          :dragging="false"
          animation="BMAP_ANIMATION_DROP"
          :icon="{
            url: require('@/assets/locate.png'),
            size: { width: 32, height: 32 },
          }"
          @click="infoWindowOpen(index)"
        >
          <bm-info-window
            :title="vertex.title"
            :show="currentInfoWindow == index"
            @close="infoWindowClose"
          >
            {{ vertex.content }}
            <div style="margin-top: 5px; width: 220px">
              北纬{{ vertex.latitude }}'
            </div>
            <div style="width: 220px">东经{{ vertex.longitude }}'</div>
          </bm-info-window>
          <bm-label
            :content="vertex.title"
            :labelStyle="{ color: 'black', fontSize: '12px' }"
            :offset="{ width: -10, height: 30 }"
          />
        </bm-marker>
      </baidu-map>
    </div>
    <div class="dataInfo">
      <div class="background-image-wrapper">
        <el-card
          style="max-width: 600px; margin-left: 2.6vw"
          body-style="text-align: center"
          class="el-card"
        >
          <template #header>
            <div
              class="card-header"
              style="text-align: center; font-size: large; font-weight: bold"
            >
              <span>燕山大学管道MST路径系统</span>
            </div>
          </template>
          <ul
            v-infinite-scroll="load"
            class="infinite-list"
            style="overflow: auto; height: 520px"
          >
            <el-table :data="edgesData" stripe style="width: 100%">
              <el-table-column
                prop="vertex1.title"
                label="Position 1's name"
                width="180"
              />
              <el-table-column
                prop="vertex2.title"
                label="Position 2's name"
                width="180"
              />
              <el-table-column prop="distance" label="Total Distance" />
            </el-table>
            <span style="color: red; font-size: smaller"
              >温馨提示：在地图中点击点位可查看详细信息</span
            >
          </ul>
          <template #footer>
            <div
              style="
                text-align: center;
                font-size: large;
                font-weight: bold;
                color: red;
                margin-left: 4vw;
              "
            >
              管道总长度：{{ distData }}米
              <span style="font-size: 0.8vw; color: blue; margin-left: 4vw"
                >数据太少，申请添加点位点这里-></span
              >
              <el-button
                type="primary"
                style="margin-left: 16px"
                @click="drawer = true"
                :icon="Edit"
                circle
              />
              <el-drawer v-model="drawer" :direction="direction">
                <template #header>
                  <h4>添加点位</h4>
                </template>
                <el-form-item>
                  <a
                    href="https://api.map.baidu.com/lbsapi/getpoint/index.html"
                    target="_blank"
                    >请谨慎输入信息!不知道所添加位置经纬度戳我</a
                  >
                </el-form-item>
                <el-form-item label="title:">
                  <el-input
                    v-model="input.title"
                    style="width: 400px"
                    placeholder="Please input the name of this position"
                  />
                </el-form-item>
                <el-form-item label="latitude:">
                  <el-input
                    v-model="input.latitude"
                    style="width: 400px"
                    placeholder="Please input the latitude of this position"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="longitude:">
                  <el-input
                    v-model="input.longitude"
                    style="width: 400px"
                    placeholder="Please input the longitude of this position"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="content:">
                  <el-input
                    v-model="input.content"
                    style="width: 400px"
                    placeholder="Please introduce the content of this position"
                    clearable
                  />
                </el-form-item>
                <el-button type="primary" @click="onSubmit">
                  Submit
                  <el-icon class="el-icon--right">
                    <Upload />
                  </el-icon>
                </el-button>
              </el-drawer>
            </div>
          </template>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject } from "vue";
import { ElLoading, ElMessageBox,ElMessage } from "element-plus";
import { Edit, Upload } from "@element-plus/icons-vue";
// import BaiduMap from "vue-baidu-map-3x"; 不要加！！！！！！！！！！

const drawer = ref(false);

const center = ref({ longitude: 119.535, latitude: 39.9172 });
const zoom = ref(16); // zoom 范围： 3 - 19
const ready = async ({ BMap, map }) => {
  // 设置地图中心和缩放
  let point = new BMap.Point(center.value.longitude, center.value.latitude);
  map.centerAndZoom(point, zoom.value);
  drawLines(BMap, map);
};
const input = ref({
  title: "",
  latitude: "",
  longitude: "",
  content: "",
});
const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: "The pipeline minimum spanning tree system of ysu is initializing, Please wait a moment.",
    background: "rgba(0, 0, 0, 1)",
  });
  setTimeout(() => {
    loading.close();
  }, 1000);
};

const currentInfoWindow = ref(null);

const infoWindowOpen = (index) => {
  currentInfoWindow.value = index;
};

const infoWindowClose = () => {
  currentInfoWindow.value = null;
};

const vertexData = ref([]);
const distData = ref();
let edgesData = ref([]);
const axios = inject("axios");
const insertData = ref(0);

const getPoint = async () => {
  axios
    .get("Vertex/listAllVertex")
    .then((response) => {
      vertexData.value = response.data;
      console.log(vertexData.value);
    })
    .catch((error) => {
      console.error(error);
    });
};

const calculateLength = async () => {
  axios
    .post("Vertex/findDistance", {})
    .then((response) => {
      distData.value = response.data;
      console.log(distData.value);
    })
    .catch((error) => {
      console.log(error);
    });
};
const dist1 = ref();
const findDist = async () => {
  axios
    .post("Vertex/findDist", {})
    .then((response) => {
      dist1.value = response.data;
      console.log(dist1.value);
    })
    .catch((error) => {
      console.log(error);
    });
};

const findAllEdges = async () => {
  axios
    .post("Vertex/findAllEdges", {})
    .then((response) => {
      edgesData.value = response.data.map((edge) => {
        return {
          ...edge, // 保留原有的边对象属性
          distance: Math.floor(edge.distance), // 只取距离的整数部分
        };
      });
      console.log(edgesData.value);
    })
    .catch((error) => {
      console.log(error);
    });
};

const drawLines = async (BMap, map) => {
  if (!edgesData.value || edgesData.value.length === 0) {
    console.warn("No edges data to draw.");
    return;
  }
  for (const edge of edgesData.value) {
    const vertexA = new BMap.Point(edge.vertex1.longitude, edge.vertex1.latitude);
    const vertexB = new BMap.Point(edge.vertex2.longitude, edge.vertex2.latitude);
    const polyline = new BMap.Polyline([vertexA, vertexB], {
      strokeColor: "red",
      strokeWeight: 5,
      strokeOpacity: 0.9,
    });
    map.addOverlay(polyline);
    await new Promise((resolve) => setTimeout(resolve, 250));
  }
};

const onSubmit = async () => {
  await axios
    .post("Vertex/newCityInfo", {
      content:input.value.content,
      title:input.value.title,
      latitude:input.value.latitude,
      longitude:input.value.longitude
    })
    .then((response) => {
      insertData.value = response.data;
      console.log(insertData.value);
    })
    .catch((error) => {
      console.log(error);
    });

  if (insertData.value == 1) {
    ElMessage({
      message: "点位信息添加成功！",
      type: "success",
      plain: true,
    });
    insertData.value = 0;
  } else {
    ElMessage({
      message: "点位信息添加失败！",
      type: "error",
      plain: true,
    });
  }
  location.reload();
};

const initializeMap = async () => {
  await Promise.all([getPoint(), findAllEdges()]);
  drawLines(BMap, map); // 确保边和顶点数据加载完成后再调用绘制函数
};

// 初始化地图时调用
openFullScreen();
initializeMap();
findDist(); // 运行 Kruskal 算法MST
calculateLength(); // 运行 Prim 算法MST

</script>

<style scoped>
.main {
  display: flex;
  width: 100vw;
  height: 100vh;
}
.mapInfo {
  flex: 1;
}
.dataInfo {
  flex: 2;
  position: relative;
  overflow: hidden;
}

.background-image-wrapper::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-image: url("../assets/image.png");
  background-size: cover;
  background-repeat: no-repeat;
  opacity: 0.2;
  z-index: -1;
}
.background-image-wrapper {
  position: relative;
  z-index: 0;
}

.el-card {
  z-index: 1;
  background-color: #fff;
  position: relative;
}
.map {
  width: 860px;
  height: 100%;
}
.infinite-list {
  height: 300px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}
.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}
</style>